package com.shierke.Ume.ui.activity.register

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.util.Log
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.al.open.OnInputListener
import com.shierke.Ume.R
import com.shierke.Ume.base.App
import com.shierke.Ume.base.BaseActivity
import com.shierke.Ume.service.CountDownIntentService
import com.shierke.Ume.ui.activity.MainActivity
import com.shierke.Ume.util.click
import com.shierke.Ume.util.config
import com.shierke.Ume.util.startActivity
import com.shierke.Ume.viewmodel.RegisterViewModel
import com.xbxm.retrofiturlmanager.RetrofitUrlManager
import com.xbxm.supplier.crm.utils.CustomUtils
import kotlinx.android.synthetic.main.activity_verfication_code.*
import java.util.concurrent.Executors

/**
 * Create by Ybx
 * on 2020-10-11
 * Desribe:
 */
class VerificationCodeActivity : BaseActivity() {


    companion object {
        fun startActivity(context: Context, phoneNum: String, region: String) {
            context.startActivity<VerificationCodeActivity>(
                Pair("phoneNum", phoneNum),
                Pair("region", region)
            )
        }
    }


    private lateinit var viewModel: RegisterViewModel
    private val COUNT_DOWN_ACTION = javaClass.name + ".COUNTDOWN"
    private val ioExecutor = Executors.newSingleThreadExecutor()


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_verfication_code)

        LocalBroadcastManager.getInstance(this)
            .registerReceiver(receiver, IntentFilter(COUNT_DOWN_ACTION))


        val phoneNum = intent.getStringExtra("phoneNum")
        val region = intent.getStringExtra("region")


        viewModel = ViewModelProviders.of(this).get(RegisterViewModel::class.java)


        viewModel.sendCode(phoneNum, region, "0")



        login.click {
            viewModel.login(phoneNum, region, "0", editCode.text.toString())
        }


        editCode.setOnInputListener(object : OnInputListener() {
            override fun onInputFinished(content: String?) {
                login.setBackgroundResource(R.drawable.bg_login_next_bt)
                login.isEnabled = true
            }


            override fun onInputChanged(text: String?) {
                super.onInputChanged(text)

                if (!text.isNullOrEmpty()) {
                    login.setBackgroundResource(R.drawable.bg_login_code_can_not_next)
                    login.isEnabled = false
                }
            }
        })

        subScribeResult()

    }


    private fun subScribeResult() {

        viewModel.sendCodeBean.observe(this, Observer {


            if (it != null && it.returnCode == "1000") {
                CountDownIntentService.startAction(this, COUNT_DOWN_ACTION, 59000, 1000)
            }
        })



        viewModel.loginBean.observe(this, Observer {

            if (it != null && it.returnCode == "1000") {


                ioExecutor.execute {
                    CustomUtils.saveUserInfo(this, it.result)

                    config.accessToken = it.result.accessToken
                    config.tokenType = it.result.tokenType

                    RetrofitUrlManager.header =
                        "${config?.tokenType}${config?.accessToken}"

                    runOnUiThread {
                       // SettingHeadSexActivity.startActivity(this)

                        MainActivity.startActivity(this)

                        finish()
                    }
                }

            } else {

            }
        })


    }


    private var receiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {

            if (COUNT_DOWN_ACTION == intent!!.action) {

                var millis =
                    intent.getLongExtra(CountDownIntentService.EXTRA_MILLISUNTILFINISHED, 0)

                var m = millis / 1000

                if (millis <= 0L) {

                } else {
                    time.text = "${m}s"
                }
            }
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        CountDownIntentService.stopAction(this, COUNT_DOWN_ACTION)
        LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver)
    }


}